package org.jeecg.modules.simulator.factory.person;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.Getter;
import lombok.Setter;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.simulator.jsonot.NumPeopEnStationApiInfo;
import org.jeecg.modules.simulator.jsonot.ODProbabilityApiInfo;
import org.jeecg.modules.simulator.jsonot.ODRoutes;
import org.jeecg.modules.simulator.jsonot.RoutePath;
import org.jeecg.modules.simulator.model.SceneParam;
import org.jeecg.modules.simulator.model.line.Line;
import org.jeecg.modules.simulator.rooter.LineRooter;
import org.jeecg.modules.simulator.service.HistoryBizPersonLoaderService;
import org.jeecg.modules.simulator.util.RedisSimUtil;

import org.jeecg.modules.simulator.util.SpringUtil;
import org.jeecg.modules.simulator.util.UnitCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.stream.Collectors;

public class GodAssistanter {
    @Getter
    @Setter
    String sceneCode;

    RedisSimUtil redisSimUtil = new RedisSimUtil();

    @Setter
    HistoryBizPersonLoaderService historyBizPersonLoaderService;//历史人员数据
    @Getter
    Map<String, List<ODProbabilityApiInfo>> odProbabilityApiInfoMap = new HashMap<>();
    @Setter
    @Getter
    Map<String, Line> lineMap = new HashMap<>();

    @Getter
    @Setter
    //原始的路径概率有可能因为过滤的情况，在路径表中找不到对应的路径，所以需要过滤
    Map<String, List<ODProbabilityApiInfo>> odProbabilityApiInfosFilterMap = new HashMap<>();

    private final String prefixRouteName = "Simu_";


    //    全天每秒刷卡进站人数
    @Getter
    @Setter
    Map<String, Map<String, NumPeopEnStationApiInfo>> numPeopEnStationApiInfoMap = new HashMap<>();


    public GodAssistanter() {
//        this.redisTemplate = ((RedisTemplate) SpringUtil.getBean("redisTemplate"));
    }
//1、各站人员OD分配概率
    public void loadODAssignPerson() {
        SceneParam sceneparam = UnitCache.sceneParamMap.get(sceneCode);
        //1、各站人员OD分配概率
        historyBizPersonLoaderService.getRouteStatistics(sceneparam.getSceneDate(), sceneparam.getStartTimeStr(), sceneparam.getEndTimeStr());
        odProbabilityApiInfoMap = historyBizPersonLoaderService.getOdProbabilityApiInfoMap();
    }
    //4、一个时间段内每秒刷卡进站人数
    public void loadEntryStationNum() {
        SceneParam sceneparam = UnitCache.sceneParamMap.get(sceneCode);
        //4、一个时间段内每秒刷卡进站人数
        historyBizPersonLoaderService.loadNumPeopleEnByEndStation(sceneparam.getSceneDate(), sceneparam.getEndTimeStr());
        numPeopEnStationApiInfoMap = historyBizPersonLoaderService.getNumPeopEnStationApiInfoMap();


    }

    //人员数据加载
    public void loadAllDayPersonHistory() {
//        loadAllDayPersonHistory.loadHistoryPerson(this.sceneCode);
//        numPeopEnStationApiInfoMap = loadAllDayPersonHistory.getNumPeopEnStationApiInfoMap();
//        odProbabilityApiInfoMap = loadAllDayPersonHistory.getOdProbabilityApiInfoMap();

        filterPersonOdRatio();
        filterODProbabilityApiInfo();

    }

    //过滤掉od概率信息中不在路径表中的信息
    public void filterODProbabilityApiInfo() {


        for (Map.Entry<String, List<ODProbabilityApiInfo>> entry : odProbabilityApiInfoMap.entrySet()) {
            String odId = entry.getKey();

            if (odId.indexOf('_') != -1) {
                odId = odId.replace(String.valueOf('_'), "");
            }

            String odstr = prefixRouteName + odId;
            List<ODProbabilityApiInfo> filterList = entry.getValue().stream().filter(odProbabilityApiInfo -> {
                String routeId = odProbabilityApiInfo.getRouteId();
                return redisSimUtil.getRouteObject(odstr, routeId);
//                return route2PersonPathMap.containsKey(routeId);
            }).collect(Collectors.toList());
            if (!filterList.isEmpty()) {
                odProbabilityApiInfosFilterMap.put(entry.getKey(), filterList);
            }
        }
        System.out.println("odProbabilityApiInfosFilterMap=====end");

    }


    /**
     * @description: od数据处理--按要求的线路ID过滤线路信息
     * @author: renzhg
     * @date: 2024/11/15 17:14
     **/
    public void filterPersonOdRatio() {
        Map<String, List<ODProbabilityApiInfo>> odProbabilityApiInfoMap2 = new HashMap<>();
        //过滤OD概率
        odProbabilityApiInfoMap.forEach((k, v) -> {

            //根据OD的站点id，提取前两位，判断是否是参与计算的线路
            if (containsPrefixInList(k, this.lineMap.keySet())) {
                odProbabilityApiInfoMap2.put(k, v);
            }
        });
        removeEntriesNotInMap1(odProbabilityApiInfoMap2, odProbabilityApiInfoMap);
    }


    public void removeEntriesNotInMap1(Map<String, List<ODProbabilityApiInfo>> map1, Map<String, List<ODProbabilityApiInfo>> map2) {
        Iterator<Map.Entry<String, List<ODProbabilityApiInfo>>> iterator = map2.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<ODProbabilityApiInfo>> entry = iterator.next();
            if (!map1.containsKey(entry.getKey())) {
                iterator.remove(); // 删除不在 map1 中的条目
            }
        }
    }


    public boolean containsPrefixInList(String input, Set<String> stringList) {
        // 分割输入字符串
        String[] parts = input.split("_");
        // 获取前两位
        String firstPart = parts[0].substring(0, 2); // "04"
        String secondPart = parts[1].substring(0, 2); // "03"
        // 检查前两位是否在列表中
        return stringList.contains(firstPart) && stringList.contains(secondPart);
    }


    public ODRoutes getODRoutesObject(String odId) {
        return  redisSimUtil.getODRoutesObject(odId);
    }


    public List<ODRoutes> getODRoutesList(String odId) {
        return  redisSimUtil.getODRouteListObject(odId);
    }
}
